#列表
list1=[1,2,3,4,5]
list.append(6)
list.remove(3)
list[1]=8
for i in list:
    print(i)
index1=list.index(8)
print(index1)
list2=[7,8,9]
list1.append(list2)
print(list1)
for i in range(len(list2)):
    list1.append(list2[i])
print(list1)
print(list1[2:5])
list1[2]=13
list1.insert(3,14)
print(list1)
my_list=[3,"apple",9,"banana",7,"cherry",2,"date",5,"elderberry"]
my_list.append("fig")
my_list.remove("banana")
print(my_list)
my_list[4]="grape"
print(my_list.index("cherry"))
for i in my_list:
    print(i)
my_list.insert(6,"kiwi")
print(my_list[2])
print(my_list[-2])
print(my_list[2:7])
print(my_list[-1:-10:-1])
#列表进阶
11.
###对列表中的字符串进行排序，并保留数字在原位
my_list = ['fig', 'elderberry', 5, 'grape', 'kiwi', 'cherry', 9, 'apple', 3]
string=sorted([x for x in my_list if isinstance(x,str)])
result=[]
str_idx=0
for item in my_list:
    if isinstance(item,(int,float)):
        result.append(item)
    else:
        result.append(string[str_idx])
#         str_idx+=1
print(result)
#12.
print(my_list)
#列表复杂
my_list[2]='five'
my_list[6]='nine'
my_list[8]='three'
print(my_list)
#1.创建一个列表包含从1到100的所有偶数。
import random
even_numbers = [x for x in range(2, 101, 2)]
print(even_numbers[:5],even_numbers[-5:])
squarted_number=[x**2 for x in even_numbers]
print(squarted_number[:5],squarted_number[-5:])
filtered_numbers=[x for x in squarted_number if x <=1000]
print(filtered_numbers[:5],filtered_numbers[-5:])
reverse_number=even_numbers[::-1]
print(reverse_number[:10])
print(even_numbers[:10])
# print(even_numbers+[101,102,103])
# average=sum(even_numbers)/len(even_numbers)
# print(average)
# print(max(even_numbers),min(even_numbers))
# try :
#     index1=even_numbers.index(11)
# except ValueError:
#     index1=-1
# print(index1)
# str_list=[]
# for num in even_numbers:
#     str_list.append(str(num))
# print(str_list)
# print(type(str_list[1]))
# str_list=[]
# index1=0
# while index1<len(even_numbers):
#     str_list.append(str(even_numbers[index1]))
#     index1+=1
# print(str_list)
# float_number=[float(x) for x in even_numbers ]
# print(float_number[:5])
# dayu=[x for x in even_numbers if x>50]
# print(dayu)
# even_numbers.insert(2,99)
# print(even_numbers[:5])
# even_numbers.pop(49)
# print(even_numbers[48])
# new_list=[x*2 for x in even_numbers]
# print(new_list[:5])
# less_equal_50=[x for x in even_numbers if x<=50]
# more_50=[x for x in even_numbers if x>50]
# print(less_equal_50[:5])
# print(more_50[:5])
# list_dict={value:index for index,value in enumerate(even_numbers)}
# for i in list_dict.items():
#     print(i)
# for index,value in enumerate(even_numbers):
#     print(f"索引：{index}元素:{value}")
# random_element=random.choice(even_numbers)
# print(random_element)
#20将列表保存到txt文件，每个元素占一行
# with open('列表元素.txt','w') as file:
#     for x in even_numbers:
#         file.write('x'+'\n')
# #字典
# #基础
# person_info = {
#     "name": "Alex",
#     "age": 30,
#     "country": "USA",
#     "language": ["English", "Spanish"],
#     "is_student": False
# }
# print(person_info['name'])
# person_info['age']=31
# print(person_info['age'])
# person_info['height']=175
# print(person_info.pop('is_student'))
# for i in person_info.items():
#     print(i)
# if 'email' not in person_info:
#     person_info['email']='alex@example.com'
# print(person_info['email'])
# person_info['language']='English'
# print(person_info['language'])
# leng=len(person_info["language"])
# print(leng)
#9,10
# person_info["language"].append("French")
# print(person_info)
# for i in range(1,4):
#     key=f"hobby{i}"
#     value=f"hobby{i}值"
#     person_info[key]=value
# print(person_info)
#字典进阶
# employees={
#     1:{"name": "Alice",
#         "age": 30,
#         "gender": "Female",
#         "position": "Data Scientist",
#         "team": "Research",
#         "salary_history": [70000, 80000, 90000]},
#     2:{"name": "Lili",
#         "age": 22,
#         "gender": "Female",
#         "position": "AA",
#         "team": "Research",
#         "salary_history": [6000]},
#     101:{"name": "HanHan",
#         "age": 25,
#         "gender": "Male",
#         "position": "BB",
#         "team": "Research",
#         "salary_history": [5000,2000,3000]}
# }
# employees[3]={"name": "Xiaoxiao",
#         "age": 27,
#         "gender": "Female",
#         "position": "Data Scientist",
#         "team": "Research",
#         "salary_history": [70000]}
# print(f"新增员工{3}:{employees[3]['name']}")
#
# # employees.pop(3)
# # for i in employees.items():
# #     print(i)
# if 101 in employees:
#     employees[101]['age']=31
# print(f"更新后年龄：{employees[101]['age']}")
# employees[101]['salary_history'].append(95000)
# print(employees[101]['salary_history'])
# salary_history=employees[101]['salary_history']
# average_salary=sum(salary_history)/len(salary_history)
# print(average_salary)
# older_employees=[]
# for emp_id,emp_data in employees.items():
#     if emp_data['age']>25:
#         older_employees.append((emp_id,emp_data['name']))
# for emp_id,name in older_employees:
#     print(f"员工ID：{emp_id},姓名：{name}")
# for emp_id,emp_data in employees.items():
#     if 'salary_history' in emp_data and emp_data['salary_history']:
#         lastest_salary=salary_history[-1]
#         bonus=lastest_salary*0.1
#         emp_data['bonus']=bonus
#         print(f"员工{emp_id}{emp_data['name']}最新薪资{lastest_salary}奖金{bonus}")
# for emp_id,emp_data in employees.items():
#     if emp_id==101:
#         emp_data['position']="高级数据分析师"
#         print(f"员工{emp_id}{emp_data['name']}职位是{emp_data['position']}")
# employee_names_positions={}
# for emp_id,emp_data in employees.items():
#     employee_names_positions[emp_id]={
#         'name':emp_data['name'],
#         'position':emp_data['position']    }
# for emp_id,data in employee_names_positions.items():
#     print(emp_id,data['name'],data['position'])
#字符串基础
# str1="1234567o"
s="Hello Python Word!"
# print(len(str1))
# print(str1.count('o'))
# print(str1.upper())
# print(str1.lower())
# index1=s.find('Python')
# print(index1)
#替换字符串
# replace_s=s.replace('Word','universe')
# print(replace_s)
# start_with_hello=s.startswith('Hello')
# print(start_with_hello)
# end_with=s.endswith("!")
# print(end_with)
# a=s.split(",")
# print(a)
# strip_s=s.strip("!")
# print(strip_s)
# reverse_s=s[::-1]
# print(reverse_s)
# reverse_sslice_s=s[6:12]
# print(slice_s)
# replace_hello=s.replace('Hello','')
# print(replace_hello)
# concated="Hello"+ " " +"Word!"
# print(concated)
# fist_a=s.find('a')
# print(fist_a)
# last_e=s.rfind('e')
# print(last_e)
# print(s.count(' '))
# #15
# num=2
# str='123'
# print(f"{num}{str}")
# #19
# for i in s:
#     if i!=" ":
#         print(i,end='\t')
# print()
# #20
# list=[]
# for i in s:
#     if i!=" ":
#         list.append(i)
# print(list)
#字符串排序sorted函数
sorted_s=sorted(s)
print(sorted_s)
#判断字符串是否为数字
is_numeric=s.isnumeric()
print(is_numeric)
#把列表连接为一个字符串
list=["hello" ,"word" ,"python" ]
join_str=" ".join(list)
print(join_str)
#24
formmated_str="Number: %d" % 100
print(formmated_str)
#25,26
is_lower=s.islower()
print(is_lower)
is_upper=s.isupper()
print(is_upper)
num_list=[1,2,3]
join_str="-".join(map(str,num_list))
print(join_str)
o_positions=[i for i,char in enumerate(s) if char=='o']
print(o_positions)
#向字符串指定位置插入子字符串
insert_pos=7
inserted_str=s[:insert_pos]+"amazing"+s[insert_pos:]
print(inserted_str)
#字符串进阶
s="Python is great!"
print(s[::-1])
replace_str=s.replace(" ","_")
print(replace_str)
count=0
for char in s:
    if char=="t":
        count+=1
print(count)
s2="A man,a plan,a canal,Panama!"
cleaned=" ".join(char.lower() for char in s2 if char.isalpha())
is_palinrome=cleaned==cleaned[::-1]
print(is_palinrome)
index=-1
for i in range(len(s)-1):
    if s[i]=='i' and s[i+1]=='s':
        index=i
        break
print(index)
t_pos=s.find('t')
new_str=s[:t_pos+1]+"_inserted"+s[t_pos+1:]
print(new_str)
replaced = s.replace("great", "awesome", 1)
print(replaced)
half=len(s)//2
new_str=s[half:]+s[:half]
print("8",new_str)
words=s.split()
capitalized=[word.capitalized() for word in words]
print(capitalized)
money=1000
cart=[]
goods=[
    {'name':'苹果','price':15},
    {'name':'香蕉','price':14},
    {'name':'橘子','price':20},
    {'name':'牛奶','price':12}
]
print('---欢迎前来购物---')
print('商品清单【】：')
for product in goods:
    print(f"{product['name']}|{product['price']}元 ")
print(f'\n当前余额为{money}')
while True:
    user_input=input("请输入商品名称加入购物车（输入Q/q退出）：")
    found=False
    if user_input.lower()=='q':
        print('购物结束')
        break
    for product in goods:
        if user_input.lower()==product['name'].lower():
            found=True
            if money>=product['price']:
                cart.append(product)
                money-=product['price']
                print(f"恭喜购买成功，余额为{money}")
            else:
                print("穷鬼，钱不够！请到其他超市购买！")
    if not found:
        print('没有这个商品，别瞎弄')
print('购物小票')
total=0
if not cart:
    print('没有购物')
for item in cart:
     print(f"{item['name']}|{item['price']}元")
     total += item['price']
print(f'消费总额：{total}元')
print(f"剩余余额{money}")
